<?php

namespace App\V3\V3_2_6\Services;

use App\V3\V3_2_6\Models\AdminModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use mysql_xdevapi\Exception;

class UsersService
{
    const SALT = 'storage';

    static public function changePwd($data)
    {
        DB::beginTransaction();

        try {
            if(!Redis::exists($data['mobile'].'_change_pwd')) {
                return ['code' => 1, 'msg' => '您输入的验证码无效，请重试', 'data' => ''];
            }
            else {
                if($data['code'] != Redis::get($data['mobile'].'_change_pwd')) {//验证码一致
                    return ['code' => 1, 'msg' => '您输入的验证码有误，请重试', 'data' => ''];
                }

                $userInfo = AdminModel::where('username', $data['mobile'])->where([
                    'delete_flag' => 0,
                    'parent_id' => 0
                ])->first();

                if(empty($userInfo)) {
                    return ['code' => 1, 'msg' => '用户不存在', 'data' => ''];
                }

                Redis::del($data['mobile'].'_change_pwd');//修改成功后销毁验证码

                if($userInfo['password'] == md5(md5($data['password'].self::SALT))) {
                    return ['code' => 0, 'msg' => 'success', 'data' => ''];
                }
                else {
                    AdminModel::where('id', $userInfo['id'])
                        ->update(['password' => md5(md5($data['password'].self::SALT))]);
                }
            }

            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        }
        catch(\Exception $e) {
            DB::rollBack();
            Log::debug('修改密码异常:'.var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }

    //注销账号
    static public function logOff($userId)
    {
        AdminModel::where('id', $userId)->update(['delete_flag' => 1]);
        AdminModel::where('parent_id', $userId)->update(['delete_flag' => 1]);
        return true;
    }
    //开启自动出入库开头
    static public function changeAutoStorageSwitch($data){
        DB::beginTransaction();
        try {
            AdminModel::where('id', $data['user_id'])->update(['auto_storage_switch' => $data['switch_flag']]);
            AdminModel::where('parent_id', $data['user_id'])->update(['auto_storage_switch'  => $data['switch_flag']]);
            DB::commit();
            return ['code'=>0,'msg'=>'success','data'=>''];
        }catch (\Exception $e){
            Log::debug('自动开启出入库异常:'.var_export($e->getMessage(), true));
            return ['code'=>0,'msg'=>'开启失败','data'=>''];
        }

    }
}
